

#include <nlohmann/json.hpp>
#include <iostream>
#include <string>

// 你的结构体
struct Person {
    std::string name;
    int age{};
    double salary{};
};

// 自动生成 to_json / from_json
NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(Person, name, age, salary)


// 再定义一个新结构体，无需额外代码！
struct Config {
    bool debug{};
    int max_connections{};
    std::string log_level{};
};
NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(Config, debug, max_connections, log_level);




template<typename T>
bool update_field_via_json(T& obj, const std::string& field, const std::string& value_str) {
    nlohmann::json j = obj; // 序列化当前对象

    if (!j.contains(field)) {
        return false; // 字段不存在
    }

    auto& orig_val = j[field];
    try {
        if (orig_val.is_string()) {
            j[field] = value_str;
        }
       else if (orig_val.is_number_integer()) {
            j[field] = std::stoll(value_str); // 更安全：支持 long long
        }
        else if (orig_val.is_number_float()) {
            j[field] = std::stod(value_str);
        }
        else if (orig_val.is_boolean()) {
            // 支持 "true"/"false", "1"/"0"
            std::string lower = value_str;
            std::transform(lower.begin(), lower.end(), lower.begin(),
                [](unsigned char c) { return std::tolower(c); });
            if (lower == "true" || lower == "1") {
                j[field] = true;
            }
            else if (lower == "false" || lower == "0") {
                j[field] = false;
            }
            else {
                return false; 
            }
        }
        else {
            return false; 
        }



        obj = j.get<T>();
        return true;
    }
    catch (...) {
        return false; // 转换异常（如 stoi("abc")）
    }


}

// ============ 测试 ============
int main() {
    Person p{ "Alice", 30, 8888.88 };
    std::cout << "Before: " << p.name << ", " << p.age << "\n";

    if (update_field_via_json(p, "age", "35")) {
        std::cout << "After age update: " << p.age << "\n";
    }

    update_field_via_json(p, "name", "Alice2 Cooper");
    std::cout << "Name2 now: " << p.name << "\n";



    Config cfg{ false, 100, "info" };
    update_field_via_json(cfg, "debug", "true");
    update_field_via_json(cfg, "max_connections", "1323");

    std::cout << "Config: debug=" << cfg.debug
        << ", max_conn=" << cfg.max_connections << "\n";

    return 0;
}


